package com.wjm.blog.common.util;

import com.wjm.blog.common.base.response.ValidationResult;
import com.wjm.blog.common.enums.ResponseEnum;
import com.wjm.blog.common.exception.BizException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * VO实体校验工具类
 *
 * @author Ailos
 * @version 1.0
 * @date 2020/5/18 14:10
 */
public class ValidationUtil {
    private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    /**
     * 对象参数校验
     *
     * @param obj 参数对象
     * @param <T> 校验结果
     * @return
     */
    public static <T> ValidationResult validateEntity(T obj) {
        ValidationResult result = new ValidationResult();
        Set<ConstraintViolation<T>> set = validator.validate(obj, Default.class);
        if (set != null && set.size() != 0) {
            result.setHasErrors(true);
            List<String> errorMsg = new ArrayList();
            for (ConstraintViolation<T> cv : set) {
                errorMsg.add(cv.getMessage());
            }
            result.setErrorMsg(errorMsg);
        }
        return result;
    }

    /**
     * 参数校验并抛出异常
     *
     * @param obj       参数对象
     * @param paramName 参数名称
     * @return void
     * @throws Exception
     * @author Ailos
     * @date 2020/5/18 14:42
     * @version 1.0
     */
    public static <T> void validate(T obj, String paramName) {
        // 校验是否为空
        if (StringUtil.isEmpty(obj)) {
            throw new BizException(ResponseEnum.PARAM_NOT_NULL, paramName);
        }

        // 对象校验
        ValidationResult result = validateEntity(obj);
        if (result.isHasErrors()) {
            throw new BizException(ResponseEnum.ERROR.getCode(), result.getErrorMsg().toString());
        }
    }
}
